package mest.service.cxj.impl;

import mest.VO.cxj.FinancialOtherIncomeRecordVO;
import mest.dao.cxj.FinancialOtherIncomeDao;
import mest.dao.cxj.PlanOtherIncomeDao;
import mest.entity.FinancialOtherIncome;
import mest.entity.FinancialOtherIncomeRecord;
import mest.entity.PlanOtherIncome;
import mest.util.MoneyUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import mest.dao.cxj.FinancialOtherIncomeRecordDao;
import mest.service.cxj.FinancialOtherIncomeRecordService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class FinancialOtherIncomeRecordServiceImpl implements FinancialOtherIncomeRecordService {

    @Resource
    private FinancialOtherIncomeRecordDao financialOtherIncomeRecordDao;

    @Resource
    private PlanOtherIncomeDao planOtherIncomeDao;

    @Resource
    private FinancialOtherIncomeDao financialOtherIncomeDao;

    @Override
    public Integer insertFinancialOtherIncomeRecord(FinancialOtherIncomeRecord foir, String theirDb) throws Exception {
        FinancialOtherIncome financialOtherIncome = financialOtherIncomeDao.selectFinancialOtherIncomeById(foir.getFoicId(), theirDb);
        PlanOtherIncome planOtherIncome = planOtherIncomeDao.selectPlanOtherIncomeById(financialOtherIncome.getPoicId(), theirDb);
        BigDecimal financialMoney = MoneyUtil.add(financialOtherIncome.getHasBennMoney(), foir.getThisMoney()); //实际收款
        BigDecimal planMoney = MoneyUtil.add(planOtherIncome.getHasBennMoney(), foir.getThisMoney());  //计划收款
        Integer i1 = financialOtherIncomeDao.updateFinancialOtherIncomeByMoney(foir.getFoicId(), financialMoney, theirDb);
        Integer i2 = planOtherIncomeDao.updatePlanOtherIncomeByMoney(financialOtherIncome.getPoicId(), planMoney, theirDb);
        if (i1 > 0 && i2 > 0) {
            return financialOtherIncomeRecordDao.insertFinancialOtherIncomeRecord(foir, theirDb);
        } else {
            throw new Exception("系统异常,请联系管理员");
        }
    }

    @Override
    public List<FinancialOtherIncomeRecordVO> selectAllFinancialOtherIncomeRecordById(Integer page, Integer limit, Integer foicId, String theirDb) {
        return financialOtherIncomeRecordDao.selectAllFinancialOtherIncomeRecordById((page - 1) * limit, limit, foicId, theirDb);
    }

    @Override
    public Integer selectCountFinancialOtherIncomeRecordById(Integer foicId, String theirDb) {
        return financialOtherIncomeRecordDao.selectCountFinancialOtherIncomeRecordById(foicId, theirDb);
    }

}
